import knowService from '@/api/services/knowService';
import FilePreviewer from '@/pages/components/fileviewer/FilePreviewer';
import { DuplicateCollection, FilePreInfoType, KnowSimilarityCollection } from '@/types/know/know';
import { useUpdate } from 'ahooks';
import { Button, Divider, message, Modal, ModalProps, Popconfirm, Select } from 'antd';
import dayjs from 'dayjs';
import { useEffect, useMemo, useState } from 'react';
import { useParams } from '@/router/hooks';
interface Props extends ModalProps {
  collection?: KnowSimilarityCollection;
  setCollection?: (collection: KnowSimilarityCollection) => void;
  refresh?: () => void;
  completed?: () => void;
}
const FileCompareModal = ({
  collection,
  setCollection,
  onCancel,
  refresh,
  completed,
  open,
  ...props
}: Props) => {
  const [mainFileLoading, setMainFileLoading] = useState(false);
  const [subFileLoading, setSubFileLoading] = useState(false);
  const [selectedSubCollection, setSelectedCollection] = useState<DuplicateCollection | null>(null);
  const [selectedSubKey, setSelectedSubKey] = useState<string | undefined>('');
  const [collectionInfos, setCollectionInfos] = useState<Record<string, FilePreInfoType>>({});
  const [refreshKey, setRefreshKey] = useState(0);
  const { appId = '' } = useParams() as { appId: string };

  const [loading1, setLoading1] = useState(false);
  const [loading2, setLoading2] = useState(false);

  const update = useUpdate();
  const options = useMemo(() => {
    return collection?.duplicateList
      ?.filter((item) => !item.isDeleted)
      .map((item) => {
        return {
          label: item.fileName,
          value: item.collectionId,
        };
      });
  }, [collection]);

  const onProcessSimilarity = async (
    item: DuplicateCollection | KnowSimilarityCollection,
    is_keep: boolean,
    isMain: boolean,
  ) => {
    try {
      const res = await knowService.postProcessSimilarity({
        collection_id: item.collectionId,
        is_keep,
        app_id: appId,
      });
      collectionInfos[item?.collectionId!].forbid = !is_keep;
      item.forbid = !is_keep;
      item.isDeleted = !is_keep;
      item.status = 1;
      update();
      message.success('操作成功');
      refresh && refresh();
      if (!is_keep) {
        const list = collection?.duplicateList?.filter((item) => !item.isDeleted);
        const newCollection = { ...collection, duplicateList: list };
        newCollection && setCollection && setCollection(newCollection);
      }

      if (
        (isMain && !is_keep) ||
        (collection &&
          collection.status == 1 &&
          !collection.duplicateList?.find((item) => item.status == 0))
      ) {
        message.success('全部文件均已处理！');
        completed && completed();
      }
    } catch (error) {
      console.log(error);
    } finally {
      setLoading1(false);
      setLoading2(false);
    }
  };

  const getCollectionInfos = async () => {
    try {
      if (!collection || !open) {
        return;
      }
      const res = await knowService.getSimilarityPreviewInfo({
        id: collection?._id!,
        appId,
      });
      // setSelectedCollection(res);
      setCollectionInfos(res);
    } catch (error) {
      console.error(error);
    }
  };

  useEffect(() => {
    if (collection && collection?.duplicateList?.length > 0) {
      const subCollection = collection?.duplicateList[0];
      setSelectedCollection(subCollection);
      setSelectedSubKey(subCollection.collectionId);
      getCollectionInfos();
    } else {
      setSelectedCollection(null);
      setSelectedSubKey(undefined);
    }
  }, [collection]);

  return (
    <Modal
      // closable={false}
      open={open}
      destroyOnClose={true}
      maskClosable={false}
      onCancel={onCancel}
      width={'90%'}
      style={{ top: '1vh' }}
      {...props}
      footer={null}
    >
      <div className="flex h-full flex-col" style={{ height: 'calc(95vh - 30px)' }}>
        <div className="flex">
          <span>处理重复知识</span>
          <Divider type="vertical" />
          <span className="text-[#8C8C8C]">相似文档 {collection?.duplicateList?.length || 0}</span>
          {/* <span className="ml-4 text-[#8C8C8C]">
            已处理 {collection?.duplicateList.filter((item) => item.status === 1).length || 0}
          </span> */}
          {/* <div className="ml-auto mr-10">
            <span>相似度 {(selectedSubCollection?.similarity || 0) * 100}%</span>
          </div> */}
          <div className="ml-auto mr-10">
            <span>
              相似度{' '}
              {(() => {
                // 检查对象和属性是否存在
                if (
                  !selectedSubCollection ||
                  selectedSubCollection.similarity === undefined ||
                  selectedSubCollection.similarity === null
                ) {
                  return '0%';
                }

                // 确保是数字类型
                const similarityValue =
                  typeof selectedSubCollection.similarity === 'number'
                    ? selectedSubCollection.similarity
                    : parseFloat(selectedSubCollection.similarity) || 0;

                // 处理数值并格式化，限制在0-100%范围内
                const percentage = Math.max(0, Math.min(100, similarityValue * 100));

                // 转为字符串，去除末尾的0和不必要的小数点
                return `${parseFloat(percentage.toFixed(2))}%`;
              })()}
            </span>
          </div>
        </div>
        <div className="mt-4 grid flex-1 gap-4 overflow-hidden md:grid-cols-1 lg:grid-cols-2">
          <div className="flex h-full w-full flex-col overflow-hidden">
            <div className="flex h-full w-full flex-col overflow-hidden bg-[#EEEEEE]">
              <div className="ml-4 mt-4">
                <span>{collection?.fileName}</span>
                <div className="flex gap-6 text-xs">
                  <div>
                    {collection?.status === 1 ? (
                      <span className="text-primary">文档已处理</span>
                    ) : (
                      <span className="text-[#FF4D00]">文档未处理</span>
                    )}
                  </div>
                  <span className="text-[#A5A9BB]">知识库: {collection?.datasetName}</span>
                  <span className="text-[#A5A9BB]">
                    导入时间: {dayjs(collection?.createTime).format('YYYY-MM-DD HH:mm:ss')}
                  </span>
                </div>
              </div>
              <div className="relative mt-2 h-full w-full flex-1 overflow-hidden p-4">
                <FilePreviewer
                  loading={mainFileLoading}
                  setLoading={setMainFileLoading}
                  previewUrl={
                    collection?.fileName?.endsWith('.md')
                      ? collectionInfos[collection?.collectionId!]?.fileUrl!
                      : collectionInfos[collection?.collectionId!]?.previewUrl!
                  }
                  fileName={collection?.fileName}
                />
              </div>
            </div>
            <div className="mt-4 flex items-center justify-center gap-4">
              <Button
                loading={loading1}
                type={
                  collectionInfos[collection?.collectionId!]?.forbid === true
                    ? 'default'
                    : 'primary'
                }
                style={{ width: '80px', borderRadius: '50px' }}
                onClick={() => {
                  setLoading1(true);
                  onProcessSimilarity(collection!, true, true);
                }}
              >
                保 留
              </Button>
              <Popconfirm
                title="您确定要去除该文档，去除后文档不可恢复?"
                onConfirm={() => {
                  setLoading1(true);
                  onProcessSimilarity(collection!, false, true);
                }}
                okText="确定"
                cancelText="取消"
              >
                <Button
                  loading={loading1}
                  type={
                    collectionInfos[collection?.collectionId!]?.forbid === true
                      ? 'primary'
                      : 'default'
                  }
                  style={{ width: '80px', borderRadius: '50px' }}
                >
                  去 除
                </Button>
              </Popconfirm>
            </div>
          </div>
          {collection && collection?.duplicateList?.length > 0 && (
            <div className="flex h-full w-full flex-col overflow-hidden">
              <div className="flex h-full w-full flex-col overflow-hidden bg-[#EEEEEE]">
                <div className="ml-4 mt-4">
                  <div className="ml-[-11px] w-full">
                    <Select
                      value={selectedSubKey}
                      onChange={(e) => {
                        const selectedItem = collection?.duplicateList.find(
                          (item) => item.collectionId === e,
                        );
                        setSelectedSubKey(e);
                        setSelectedCollection(selectedItem!);
                      }}
                      className="know-document-select w-full"
                      // bordered={false}
                      options={options}
                    />
                    {/* {selectedSubCollection?.name} */}
                  </div>
                  <div className="flex gap-6 text-xs">
                    <div>
                      {selectedSubCollection?.status === 1 ? (
                        <span className="text-primary">文档已处理</span>
                      ) : (
                        <span className="text-[#FF4D00]">文档未处理</span>
                      )}
                    </div>
                    <span className="text-[#A5A9BB]">
                      知识库: {selectedSubCollection?.datasetName}
                    </span>
                    <span className="text-[#A5A9BB]">
                      导入时间:{' '}
                      {dayjs(selectedSubCollection?.createTime).format('YYYY-MM-DD HH:mm:ss')}
                    </span>
                  </div>
                </div>
                <div className="relative h-full w-full flex-1 overflow-hidden p-4">
                  <FilePreviewer
                    loading={subFileLoading}
                    setLoading={setSubFileLoading}
                    previewUrl={
                      selectedSubCollection?.fileName.endsWith('.md')
                        ? collectionInfos[selectedSubCollection?.collectionId!]?.fileUrl!
                        : collectionInfos[selectedSubCollection?.collectionId!]?.previewUrl!
                    }
                    fileName={selectedSubCollection?.fileName}
                  />
                </div>
              </div>
              <div className="mt-4 flex items-center justify-center gap-4">
                <Button
                  loading={loading2}
                  type={
                    collectionInfos[selectedSubCollection?.collectionId!]?.forbid === true
                      ? 'default'
                      : 'primary'
                  }
                  style={{ width: '80px', borderRadius: '50px' }}
                  onClick={() => {
                    setLoading2(true);
                    onProcessSimilarity(selectedSubCollection!, true, false);
                  }}
                >
                  保 留
                </Button>
                <Popconfirm
                  title="您确定要去除该文档吗？去除后文档不可恢复。"
                  onConfirm={() => {
                    setLoading2(true);
                    onProcessSimilarity(selectedSubCollection!, false, false);
                  }}
                  okText="确定"
                  cancelText="取消"
                >
                  <Button
                    loading={loading2}
                    type={
                      collectionInfos[selectedSubCollection?.collectionId!]?.forbid === true
                        ? 'primary'
                        : 'default'
                    }
                    style={{ width: '80px', borderRadius: '50px' }}
                  >
                    去 除
                  </Button>
                </Popconfirm>
              </div>
            </div>
          )}
          {collection?.duplicateList?.length === 0 && (
            <div className="flex h-full items-center justify-center">无相似文档</div>
          )}
        </div>
      </div>
    </Modal>
  );
};

export default FileCompareModal;
